package com.withoutwords;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.util.Log;

import com.google.android.gcm.GCMBaseIntentService;
import com.withoutwords.engine.GameController;
import com.withoutwords.engine.comminication.ServerNotifications;
import com.withoutwords.engine.settings.Settings;

public class GCMIntentService extends GCMBaseIntentService {

	public static final String SenderID = "1048214597802";

	@Override
	protected void onError(Context context, String errorId) {
		// TODO Auto-generated method stub

	}

	@Override
	protected String[] getSenderIds(Context context) {
		// TODO Auto-generated method stub
		return new String[] { SenderID };
	}

	@Override
	protected void onMessage(Context context, Intent intent) {

		// Toast.makeText(context, "push message", Toast.LENGTH_LONG).show();
		String payload = intent.getStringExtra("msg");
		if (payload != null) {
			int iKeyIndex = 0;
			int iSepIndex = 0;
			Bundle params = new Bundle();
			int notifType = -1;
			int iEndIndex = -1;
			while (iEndIndex != payload.length()) {
				iKeyIndex = iEndIndex + 1;
				iSepIndex = payload.indexOf("=", iKeyIndex);
				iEndIndex = payload.indexOf(":", iSepIndex);
				if (iEndIndex == -1) {
					iEndIndex = payload.length();

				}
				String keyParam = payload.substring(iKeyIndex, iSepIndex);
				String valueParam = payload.substring(iSepIndex + 1, iEndIndex);
				if (keyParam != null && valueParam != null)
					params.putString(keyParam, valueParam);

			}

			try {
				notifType = new Integer(params.getString("nType"));
				ServerNotifications notificationType = ServerNotifications.values()[notifType];
				GameController.getInstance().setApplicatoinContext(context.getApplicationContext());
				GameController.getInstance().onServerNotificationRecieved(
						notificationType, params);
			} catch (Exception e) {
				// TODO: handle exception
			}

		
		}

	}

	@Override
	protected void onRegistered(Context context, String regId) {
		Log.e("GCM Service onRegistered", " old regId = "
				+ Settings.getInstance().getPushToken());
		Log.e("GCM Service onRegistered", " new regId = " + regId);
		if (regId != null) {

			Settings.getInstance().setPushToken(regId);
		}

	}

	@Override
	protected void onUnregistered(Context context, String regId) {
		Log.e("GCM Service onUnregistered", " new regId = " + regId);
		Settings.getInstance().setPushToken("");
	}

	@Override
	protected boolean onRecoverableError(Context context, String errorId) {
		return true;
	}

}
